<?php
namespace app\index\controller;

use app\common\model\AlipayOrders;
use app\common\model\Mirror as MirrorModel;
use app\common\model\Query;
use app\common\model\Software as SoftwareModel;
use bigDream\CdnUrlAuth\Aliyun;
use bigDream\CdnUrlAuth\Tencent;
use bigDream\thinkJump\Jump;
use think\facade\Config;
use think\facade\Request;

/**
 * Class Software
 * @package app\index\controller
 * @author jwj <jwjbjg@gmail.com>
 * @copyright jwj
 */
class Software
{
    public function info()
    {
        $info = SoftwareModel::with(['article' => function(Query $query) {
            $query->order('update_time', 'desc')
                ->field(['id', 'category_id', 'title'])
                ->withLimit(15);
        }])
            ->where('id', Request::param('id/d'))
            ->find();
        if (null === $info) Jump::error('内容不存在');

        if (Request::has('out_trade_no', 'cookie', true)) {
            $orders =  AlipayOrders::findOutTradeNo(Request::cookie('out_trade_no'));
            if (null === $orders) {
                // 订单不存在
                $oss_url = 'javascript:';
            } elseif (1 != $orders['status']) {
                // 订单未支付
                $oss_url = 'javascript:';
            } elseif (strtotime($orders['create_time']) + 86400 * 7 < time()) {
                // 已过期
                $oss_url = 'javascript:';
            } else {
                $oss_url = $info['oss_url'];
            }
        } else {
            $oss_url = 'javascript:';
        }

        return view('', [
            'info'    => $info,
            'oss_url' => $oss_url,
        ]);
    }

    /**
     * 下载页
     * @return \think\response\Redirect|\think\response\View
     */
    public function download()
    {
        $mirror = MirrorModel::where('status', 1)->where('id', Request::param('mirror'))->find();
        if (null === $mirror) Jump::error('下载点不存在');

        $software = SoftwareModel::where('id', Request::param('id'))->find();
        if (null === $software) Jump::error('内容不存在');

        // 是否是付费节点
        if ($mirror['paid']) {
            $payStatus = AlipayOrders::existsPay(Request::cookie('out_trade_no'));
            // 是否已支付
            if (1 !== $payStatus) {
                return view('', [
                    'mirror'    => $mirror,
                    'software'  => $software,
                    'payStatus' => $payStatus,
                ]);
            }
        }

        switch ($mirror['type']) {
            case 'Aliyun::typeA':
                $url = (new Aliyun($mirror['secret'], 'auth_key', $mirror['expire']))
                    ->typeA($mirror['base_url'] . $software['url']);
                break;
            case 'Tencent::typeA':
                $url = (new Tencent($mirror['secret']))->typeA($mirror['base_url'] . $software['url']);
                break;
            case 'other':
            default:
                $url = $mirror['base_url'] . $software['url'];
                break;
        }

        $software->where('id', $software['id'])->inc('download_count')->update();

        return redirect($url);
    }

    /**
     * 获取下载节点
     * @return \think\response\Json
     */
    public function mirror()
    {
        $info = SoftwareModel::where('id', Request::param('id/d'))->cache(3600)->find();
        if (null === $info) Jump::error('内容不存在');

        $list = [];

        $mirrorResult = MirrorModel::where('status', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        foreach ($mirrorResult as $key => $mirror) {
            // 软件已废弃，当前节点不储存废弃内容则跳过
            if ($info['discard'] && !$mirror['storage_discard']) continue;

            $list[$key] = [
                'name'     => 'mirror-' . $mirror['id'],
                'title'    => $mirror['name'],
                'url'      => (string)url('Software/download', ['mirror' => $mirror['id'], 'id' => $info['id']]),
                'need_pay' => false,
                'badge'    => []
            ];

            // 是否是付费节点
            if ($mirror['paid']) {
                $list[$key]['badge']['付费'] =  'bg-danger';
            }
        }

        return json([
            'code' => 0,
            'msg'  => '获取成功',
            'data' => $list,
        ]);
    }
}